job "user" {
  datacenters = ["dc1"]
  type        = "service"

  group "user" {
    count = 1  # 初始实例数

    network {
      port "grpc" {
        static = 8001
      }
    }

    service {
      name = "user"
      tags = ["grpc", "user"]
      port = "grpc"

      check {
        type     = "grpc"
        interval = "10s"
        timeout  = "2s"
        method   = "/"
      }
    }

    scaling {
      enabled = true
      min     = 1
      max     = 4

      policy {
        cooldown  = "5m"
        evaluation_interval = "30s"

        # 基于CPU使用率的扩缩容
        metrics {
          type = "prometheus"
          source = "http://127.0.0.1:9090"
          query = <<EOT
              sum(rate(container_cpu_usage_seconds_total{job="user"}[1m]))
              /
              sum(container_spec_cpu_quota{job="user"} / container_spec_cpu_period{job="user"})
              * 100
            EOT
        }

        target {
          nomad_autoscaler {
            policy = "target-value"
            target_value = 70  # CPU使用率达到70%时扩容
          }
        }
      }
    }

    task "user" {
      driver = "docker"

      config {
        image = "registry.cn-hangzhou.aliyuncs.com/my_public_images/user:latest"
        ports = ["grpc"]
      }

      resources {
        cpu    = 500  # MHz
        memory = 256  # MB
      }

      env {
        NOMAD_HOST_IP = "${NOMAD_HOST_IP_grpc}"
        PORT          = "${NOMAD_PORT_grpc}"
        JAEGER_AGENT_HOST = "jaeger-agent.service.consul"
        JAEGER_AGENT_PORT = "6831"
      }
    }
  }
}